/* Copyright (c) 2009 - 2010 98Labs Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sbal89.map.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.data.spreadsheet.CellEntry;
import com.sbal89.map.util.SDAUtil;
import com.sbal89.map.util.XMLUtil;

@SuppressWarnings("serial")
public class PRXmlServlet extends BaseServlet {
	private Logger log = Logger.getLogger(this.getClass().getName());
	
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String key = request.getParameter("key");
		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
		xml += "<provinces>\n";

		try {
			int minRow = 2;
			int maxRow = 83;
			int minCol = 2;
			int maxCol = 12;

			List<CellEntry> cellEntries = SDAUtil.getCells(getSprService(), key, minRow, maxRow, minCol, maxCol);
			xml += XMLUtil.getPovinces(cellEntries, minRow);
			log.info("Generated PR XML request for key=" + key);
			log.info(xml);
		} catch (Exception e) {
			log.severe("Failed to generate PR XML request for key=" + key);
			e.printStackTrace();
		}
		
		xml += "</provinces>\n";
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Expires", "-1");
		response.setContentType("text/xml");
		PrintWriter pw = response.getWriter();
		pw.print(xml);
		pw.flush();
    }
}
